<?php
/*
 * @description: Контроллер для работы админпанели
 * @copyright Copyright (c) 2012-2017 Marin V. , Tykva A. , Kozel R. , Sokolov D.
 * @version 1.0
 * @link http://lecturebox.ru
*/

class AdminController extends Model_Controller
{
    public function init()
    {
        parent::init();
        $staticSalt = $this->getFrontController() //извлекаем настройку salt
                ->getParam('bootstrap')->getOption('salt'); //из application.ini        
        Zend_Registry::set('staticSalt', $staticSalt); //заносим staticSalt в Zend_Registry 
    }

    public function indexAction()
    {
        $session = new Zend_Session_Namespace('lectureBox.l10n');
            if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                        $this->view->title = 'Панель администратора';
                        $this->view->headTitle($this->view->title, 'PREPEND');
                        $this->view->headMeta()->appendName('description',
                                'Панель администратора. Управляй миром.');
                    } else {
                        $this->view->title = 'Admin panel';
                        $this->view->headTitle($this->view->title, 'PREPEND');
                        $this->view->headMeta()->appendName('description',
                                'Admin panel. Control the world.');
                    }
            }
    }
    
    /**
     * Администрирование курсов
     */
    public function coursesAction() 
    {
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($session->locale) {
            if($session->locale == 'ru_RU'){
                 $this->view->title = 'Администрирование всех курсов';
        $this->view->headMeta()->appendName('description',
                'Курсы лектора');
            } else {
                 $this->view->title = 'Administration of all courses';
        $this->view->headMeta()->appendName('description',
                'lecturer courses');
            }
        } 

        $page = (int) $this->getRequest()->getParam('page', 1);

        $work = new Model_Course();
        $this->view->pages = $work->getPaginatorRows($page, 5, 0, 0);

        if(count($this->view->pages))
        {
            foreach($this->view->pages as $item)
                break;
        }
        $this->view->user_id = $this->user_id;        
    }
    
    /**
     * Администрирование лекций
     */
    public function lecturesAction()
    {
        $page = (int) $this->getRequest()->getParam('page', 1);

        $work = new Model_Lecture();
        $this->view->pages = $work->getPaginatorRows($page, 5, 0, 0);

        if(count($this->view->pages))
        {
            foreach($this->view->pages as $item)
                break;
            //$this->view->title = 'LectureBox.ru';
            $session = new Zend_Session_Namespace('lectureBox.l10n');
            if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                        $this->view->headTitle('Главная', 'PREPEND');
                        $this->view->headMeta()->appendName('description',
                            'Все лекции в одной коробке');
                    } else {
                        $this->view->headTitle('MainPage', 'PREPEND');
                        $this->view->headMeta()->appendName('description',
                            'All lectures in one box');
                    }
            }
        }
        $this->view->user_id = $this->user_id;
    }

    /**
     * Администрирование пользователей
     */
    public function usersAction()
    {
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($session->locale) {
            if($session->locale == 'ru_RU'){
                $this->view->title = 'Администрирование пользователей';

            } else {
                $this->view->title = 'Administration of Users ';
            }
        }

        if ($session->locale) {
           if($session->locale == 'ru_RU'){
               $this->view->headMeta()->appendName('description',
               'Администрирование пользователей, удаление.');
               $this->view->headTitle('Главная', 'PREPEND'); 
           } else {
               $this->view->headMeta()->appendName('description',
               'User administration, remove');
               $this->view->headTitle('Admin panel', 'PREPEND'); 
           }
        }
       
//        $this->view->headTitle($this->view->title, 'PREPEND');        
//        $course = new Model_Course();
//        $this->view->courses = $course->getAllCourses();

        $page = (int) $this->getRequest()->getParam('page', 1);

        $work = new Model_User();
        $this->view->pages = $work->getPaginatorRows($page, 5, 0, 0);

        if(count($this->view->pages))
        {
            foreach($this->view->pages as $item)
                break;
        }
        $this->view->user_id = $this->user_id;     
    }
    
     /**
     * Администрирование пользователей
     */
    public function deluserAction()
    {
        $uid = (int) $this->getRequest()->getParam('uid');
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        
        $lecture = new Model_User();            
        $lecture->delUser($uid);
        
        if ($session->locale) {
            if($session->locale == 'ru_RU'){
                $this->_helper->flashMessenger->addMessage(
                '<li class="text-success">Пользователь удален!</li>');
            } else {
                $this->_helper->flashMessenger->addMessage(
                '<li class="text-success">User removed!</li>');
            }
        }
        $this->_helper->redirector('users', 'admin');
    }
    
     /**
     * Администрирование разделов
     */
    public function subjectsAction()
    {
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        
        $page = (int) $this->getRequest()->getParam('page', 1);

        $work = new Model_Subject();
        $this->view->pages = $work->getPaginatorRows($page, 5, 0, 0);

        if(count($this->view->pages))
        {
            foreach($this->view->pages as $item)
                break;
            if ($session->locale) {
                if($session->locale == 'ru_RU'){
                    $this->view->title = 'Администрирование разделов';
                    $this->view->headMeta()->appendName('description',
                    'Администрирование разделов, редактирование, добавление, удаление.');
                    $this->view->headTitle('Админ панель', 'PREPEND'); 

                } else {
                    $this->view->title = 'Administration of Sections';
                    $this->view->headMeta()->appendName('description',
                    'Administration of Sections, edit, add, delete.');
                    $this->view->headTitle('Admin panel', 'PREPEND'); 
                }
            }
        }        
        
    }
    
    /**
    * Смена роли пользователя
    */
    public function changeroleAction()
    {
        $id = (int) $this->getRequest()->getParam('uid');
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($session->locale) {
            if($session->locale == 'ru_RU'){
                 $this->view->title = 'Изменить роль пользователя';
                    $this->view->headTitle($this->view->title, 'PREPEND');
                    $this->view->headMeta()->appendName('description',
                    'Изменить роль. Страница редактирования роли пользователя.');
            }else{
                 $this->view->title = 'Change user role';
                 $this->view->headTitle($this->view->title, 'PREPEND');
                 $this->view->headMeta()->appendName('description',
                        'Change user role page.');
            }
        }
        
        // Проверка прав доступа
        $acl = Zend_Registry::get('acl');
        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $role = Bootstrap::getRole($identity->role);

        if(!$acl->isAllowed($role, 'mvc:admin', 'changerole'))
            return $this->_forward('login');
        
        // Используем форму
        $form = new Form_Signup();
        $form->removeElement('username');
        $form->removeElement('password');
        $form->removeElement('password_confirm');
        $form->removeElement('email');
        $form->removeElement('captcha');
        $form->removeElement('role');
        //$form->addElement('role2');
        $form->getElement('role2')->setLabel('Выберите новую роль:');

        // Меняем action формы
        $form->setAction(Zend_Navigation_Page_Mvc::factory(array(
                    'action' => 'changerole',
                    'controller' => 'admin'
                ))->getHref());
        // Меняем текст на кнопке submit
        $form->getElement('submit')->setLabel('Сохранить данные');
        
        $uidp = new Zend_Form_Element_Hidden('uid');
        $uidp->addFilter('Int'); 
        $form->addElements(array($uidp));
        
        $uid = $this->getParam('uid');
        
        $_dbTable = new Model_DbTable_Users();
        $select = $_dbTable->select();
        $select->where('id = ?', $uid);
        $_row = $_dbTable->fetchAll($select);
        foreach ($_row as $itemf){
            $urole = $itemf['role'];
        }   
                
        if (count($_POST)) 
        { 
            if($form->isValid($_POST))
            {
                $data = array (                    
                    'role' => $form->getValue('role2')
                );   
       
                // Сохраняем изменения в БД
                Zend_Db_Table::getDefaultAdapter()->update(
                        TABLE_PREF . 'users', $data, 'id=' . $uid);
     
                if ($session->locale) {
                    if($session->locale == 'ru_RU'){
                        $this->_helper->FlashMessenger('<li class="text-success">Сохранено</li>');
                    } else {
                    $this->_helper->FlashMessenger('<li class="text-success">Saved</li>');
                }
                }
                $this->_redirect($_SERVER['REQUEST_URI'] . '/uid/' . 
                                $uid);
            }
        }
        else
        {
            // Вставляем в форму актуальные значения полей
            $form->setDefault('uid', $id);
            $form->setDefault('role', $urole);
        }
        
        $this->view->form = $form;        
    }
    
    /**
    * Блокировка пользователя
    */
    public function blockuserAction()
    {
        $id = (int) $this->getRequest()->getParam('uid');
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        
        $lecture = new Model_User();            
        $lecture->blockUser($id);
        
        if ($session->locale) {
            if($session->locale == 'ru_RU'){
                $this->_helper->flashMessenger->addMessage(
                '<li class="text-success">Пользователь заблокирован!</li>');
            } else {
                $this->_helper->flashMessenger->addMessage(
                '<li class="text-success">User is blocked!</li>');
            }
        }
        $this->_helper->redirector('users', 'admin');
    }       
    
    /**
    * Разблокировка пользователя
    */
    public function unblockuserAction()
    {
        $id = (int) $this->getRequest()->getParam('uid');
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        
        $lecture = new Model_User();            
        $lecture->unblockUser($id);
        
        if ($session->locale) {
            if($session->locale == 'ru_RU'){
                $this->_helper->flashMessenger->addMessage(
                '<li class="text-success">Пользователь разблокирован!</li>');
            } else {
                $this->_helper->flashMessenger->addMessage(
                '<li class="text-success">User is unblocked!</li>');
            }
        }
        $this->_helper->redirector('users', 'admin');
    }
    /**
    * Добавление пользователя
    */
    public function adduserAction()
    {
        $session = new Zend_Session_Namespace('lectureBox.l10n');
        if ($session->locale) {
           if($session->locale == 'ru_RU'){
                $this->view->title = "Добавление пользователя";
                $this->view->headTitle()->append('Регистрация');
           }else {
               $this->view->title = "Adding a User";
                $this->view->headTitle()->append('Sign Up');
           }
        }
        $this->view->headMeta()->appendName('description',
                'Регистрация в системе');
        
        $form = new Form_Signup();
        $form->removeElement('captcha');
        $form->removeElement('role');
        //$form->addElement('role2');
        // Меняем action формы
        $form->setAction(Zend_Navigation_Page_Mvc::factory(array(
                    'action' => 'adduser',
                    'controller' => 'admin'
                ))->getHref());
        // Меняем текст на кнопке submit
        $form->getElement('submit')->setLabel('Добавить пользователя');        
        
        if (count($_POST) && $form->isValid($_POST)) 
        { 
            //создаем уникальную соль для хэширования
            $passwordSalt = $this->salt();
      
            $user = new Model_User();
            $user->fill($form->getValues());
            $user->role = $form->getValue('role2');
            $user->password = md5($form->getValue('password') 
                            . $passwordSalt 
                            . Zend_Registry::get('staticSalt'));
            $user->password_salt = $passwordSalt;
            $user->code = uniqid();
            $user->activated = 1;
            $user->save();

            
            if ($session->locale) {
                if($session->locale == 'ru_RU'){
                    $this->_helper->flashMessenger->addMessage(
                    '<li class="text-success">Пользователь добавлен!</li>');
                } else {
                    $this->_helper->flashMessenger->addMessage(
                    '<li class="text-success">User added!</li>');
                }
            }            
            $this->_helper->redirector('users', 'admin');
        }
        $this->view->form = $form;
    }   
    
    /**
     * Уникальная случайная строка надежной длинны
     * @return string 
     */
    public function salt()
    {
        $salt = '';
        for($i=0;$i<32;$i++)
            $salt .= mt_rand(0,9);
        return md5($salt);
    }
  
}